package com.dixiang.framework.network;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.dixiang.framework.common.QjResult;
import com.dixiang.framework.utils.Base64Utils;
import com.dixiang.framework.utils.KeyValue;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import android.app.Activity;
import android.app.Fragment;
import android.os.AsyncTask;

public class HttpAsyncTask extends AsyncTask{

	protected Activity activity;
	protected Fragment fragment;
	private final static int HTTP_SCCUESS = 0;
	private final static int HTTP_FAILURE = 1;
	private final static int HTTP_ERROR = 2;
	private final static int HTTP_UNKNOWN = 3;
    private boolean isShow = true;
	
    public HttpAsyncTask(Activity activity) {
    	this.activity = activity;
    }
    
    public HttpAsyncTask(Fragment fragment) {
    	this.fragment = fragment;
    }
    
	@Override
	protected Object doInBackground(Object... arg0) {
		try{
			String httpUrl = arg0[0].toString().trim();
			Object param = arg0[1];
			TypeToken typeToken  = ((TypeToken)arg0[2]);
			NetUICallback httpLoader = (NetUICallback)arg0[3];
			int flg = 0;
			if(arg0.length > 4) {
				String flgStr = arg0[4]+"";
				if(isNumeric(flgStr)){
					flg = Integer.parseInt(flgStr);
				}
			}
			
			KeyValue keyValue = null;
			if(param instanceof String){
				String paramStr = null;
				keyValue = HttpUtils.doGet(httpUrl, null);
			}else if(param instanceof Map){
				String paramStr = fixPostParam((Map<String,Object>)param);
				keyValue = HttpUtils.doPost(httpUrl, null);
			}
			
			if(activity == null  || activity.isFinishing()){
				return null;
			}
			
//			if(fragment == null || !fragment.isVisible()){
//				return null;
//			}
			
			parseResult(typeToken ,keyValue ,httpLoader ,flg);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	@Override
	protected void onPostExecute(Object result) {
		super.onPostExecute(result);
	}
	
	private <T> QjResult<T> parseResult(TypeToken typeToken ,KeyValue keyValue ,NetUICallback httpLoader ,int flg){
		Gson gson = new Gson();  
		java.lang.reflect.Type type = typeToken.getType();  
		  
		if(keyValue.first == HTTP_SCCUESS){
			String json = keyValue.second+"";
			QjResult<T> result = gson.fromJson(json, type);
			if (result != null && "ok".equals(result.getStatus())){
				httpLoader.onSccuess(result,flg);
			}else if(result != null && "no".equals(result.getStatus())){
				httpLoader.onFailure(result,flg);
			}else if(result == null){
				httpLoader.onFailure(result,flg); 
			}
		}else if(keyValue.first == HTTP_FAILURE){
			httpLoader.onFailure(null,flg);
		}else if(keyValue.first == HTTP_ERROR){
			httpLoader.onError(null, (Exception)keyValue.second,flg);
		}
		return null;
	}
	
	public boolean isNumeric(String str){ 
	   Pattern pattern = Pattern.compile("[0-9]*"); 
	   Matcher isNum = pattern.matcher(str);
	   if( !isNum.matches() ){
	       return false; 
	   } 
	   return true; 
	}
	
	private String fixPostParam(Map<String,Object> map) throws Exception{
		StringBuffer stringBuffer = new StringBuffer("{");
		if(map != null && !map.isEmpty()){
			for (Map.Entry<String, Object> entry : map.entrySet()) {
				stringBuffer.append("\"");
				stringBuffer.append(entry.getKey());
				stringBuffer.append("\":");
				stringBuffer.append(entry.getValue()+"");
				stringBuffer.append(",");
			}
			int index = stringBuffer.lastIndexOf(",");
			String value = stringBuffer.substring(0, stringBuffer.length()-1) +"}";
			return Base64Utils.encode(value.getBytes("UTF-8"));
		}
		return "";
	}
}
